<?php
/**
 * Created by jinqiang on 2025/8/26 9:51.
 * Copyright (c) 2025, Your Company. All rights reserved.
 */


namespace App\Http\Controllers\Om;


use App\Http\Controllers\Controller;
use App\Http\Services\Om\SalesService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\Finder\Finder;

class SalesController extends Controller
{
    public function list(Request $request, SalesService $salesService)
    {
        $this->validate($request, [
            'page' => 'required',
            'limit' => 'required'
        ]);
        $param = $request->all();
        $res = $salesService->search($param);
        return result($res);
    }

    //售罄率
    public function srate(Request $request, SalesService $salesService)
    {
        $param = $request->all();
        $res = $salesService->salesRateStatistic($param);
        return result($res);
    }

    //获取导入文件列表
    public function excelList(Request $request)
    {
        $processKey = "SALES_EXCEL_IMPORT";
        //获取正在导出的任务进度
        $cache = Cache::get($processKey) ?: [];
        $finder = new Finder();
        $files = $finder->files()->in(storage_path("cache/sales"))->name("销售单_*.xls*");
        $data = [];
        $createTimeList = [];
        foreach ($files as $file) {
            $fileName = $file->getFilename();
            $createUser = preg_match("/销售单_(.*?)_(\d{14})_.*?\.xls/is", $fileName, $d) ? $d[1] : "";
            $data[] = [
                'create_user' => $createUser,
                'create_time' => date('Y-m-d H:i:s', strtotime($d[2])),
                'name' => preg_replace("/^销售单_(.*?)_(\d{14})_/is", "", $fileName),
                'status' => ($cache['file']??"") == $fileName ? 0 : 1,
                'process' => ($cache['file']??"") == $fileName ? $cache['process'] : 100
            ];
            $createTimeList[] = strtotime($d[2]);
        }
        array_multisort($createTimeList, SORT_DESC, $data);
        return result(['data' => $data, 'cache' => $cache]);
    }

    //获取导入进度
    public function importCache()
    {
        $processKey = "SALES_EXCEL_IMPORT";
        //获取正在导出的任务进度
        $cache = Cache::get($processKey) ?: [];
        return result($cache);
    }
}
